<?php

namespace QyManage\Controller;

use QyManage\Controller\QyManageController;

/**
 *  企业管理-企业成员
 *  @author zangyilei
 */
class UserController extends QyManageController {
    /**
     *  企业成员列表
     */
    public function index() {
        $strCate_id = $this->getParam('cate_id', 0, 'int');
        $strRole_id = $this->getParam('role_id', 0, 'int');
        $company_id = $this->iCompanyId;
        $role_id = $this->iRoleId;

        if (isset($_POST['cate_id']) != false || isset($_POST['cate_id']) != null) {
            $where['qy_user_company_relat.cate_id'] = $strCate_id;
        }

        if (isset($_POST['role_id']) != false || isset($_POST['role_id']) != null) {
            $where['qy_user_company_relat.role_id'] = $strRole_id;
        }

        $where['qy_user_company_relat.company_id'] = $company_id;
        $where['qy_user_company_relat.status'] = array('EGT', 0);
        $User = D('UserCompanyRelat');
        $userArr = $User->join('qy_user b on qy_user_company_relat.user_id = b.user_id ')
                ->join('qy_company c on qy_user_company_relat.company_id = c.company_id ')
                ->join('LEFT JOIN qy_category_all d on qy_user_company_relat.cate_id = d.cate_id ')
                ->field('qy_user_company_relat.id as relat_id,
                     b.user_id,
                     b.user_name,
                     b.real_name,
                     b.phone,
                     b.photo,
                     b.position,
                     qy_user_company_relat.status,
                	 qy_user_company_relat.role_id,
                	 d.cate_id,
                	 d.cate_name')
                ->where($where)
                ->order("field(qy_user_company_relat.role_id,1,2,0)")
                ->select();

        if (empty($userArr)) {
            $this->returnList();
        }

        $arrManagerIds = array();   //管理员（含老板）
        $arrUserIds = array();      //普通成员
        foreach ($userArr as $key => &$val) {
            $val['photo'] && $val['photo'] = C('SITE_URL') . $val['photo'];
            $val['is_edit'] = 1;
            $val['is_remove'] = 1;
            if ($val['role_id'] == 1 || $val['role_id'] == 2) {
                $val['cate_name'] = '运营,客服,美工,营销';
            }

            if ($val['role_id'] == 1) {
                $val['position'] = $val['position'] ? $val['position'] : '总经理';
                $val['is_edit'] = 0;
                $val['is_remove'] = 0;
            }
            if ($role_id == 2 && $val['role_id'] == 2) {
                $val['is_edit'] = 0;
                $val['is_remove'] = 0;
            }
            if ($role_id == 0) {
                $val['is_edit'] = 0;
                $val['is_remove'] = 0;
            }

            //分别管理者（含老板）和 普通成员
            if (in_array($val['role_id'], array(1, 2))) {
                $arrManagerIds[] = $val['user_id'];
            } else {
                $arrUserIds[] = $val['user_id'];
            }
        }
        unset($val);

        $arrAllUserIds = array_merge($arrManagerIds, $arrUserIds);
        $objUserCheck = M('UserCheck');
        $arrAllUserCheckList = $objUserCheck->field('user_id,cate_id,specialty_sort')->where(array('user_id' => array('in', $arrAllUserIds)))->select();

        if (!empty($arrAllUserCheckList)) {
            foreach ($userArr as &$val) {
                foreach ($arrAllUserCheckList as &$vv) {
                    switch ($vv['cate_id']) {
                        case '1':
                            $strCateName = '运营';
                            break;
                        case '2':
                            $strCateName = '客服';
                            break;
                        case '3':
                            $strCateName = '美工';
                            break;
                        case '4':
                            $strCateName = '营销';
                            break;
                        default:
                            $strCateName = '';
                            break;
                    }
                    if ($vv['user_id'] == $val['user_id']) {
                        $levelName = $this->_checkLevel($vv['specialty_sort']);
                        $val['check_post'][] = $levelName.$strCateName;
                    }
                }
                $val['check_post'] = implode(',', $val['check_post']);
                unset($vv);
            }
            unset($val);
        }
        $this->returnList($userArr);
    }
    
    /**
     * 评测等级
     * @param type $iSpecialtySort
     * @return string
     */
    private function _checkLevel($iSpecialtySort){
        switch ($iSpecialtySort) {
            case '1':
                $level_name = '初级';
                break;
            case '2':
                $level_name = '中级';
                break;
            case '3':
                $level_name = '高级';
                break;
        }
        return $level_name;
    }

    /**
     *  添加企业成员
     */
    public function add() {
        $iPhone = $this->getParam('phone', '', 'mobile', true, '请填写正确账号码');
        $iPosition = $this->getParam('position', '', 'string', true, '请填写职位');
        $iRoleId = I("role_id");
        $iCateId = I("cate_id");
        if ($iRoleId == '请选择角色')
            $this->error("请选择角色");
        if ($iCateId == '请选择岗位')
            $this->error("请选择岗位");
        $iCompanyId = $this->iCompanyId;
        $Relat = D("UserCompanyRelat");

        //获取公司信息详情
        $CompanyInfo = $this->getCompanyInfo($iCompanyId);
        if ($CompanyInfo['status' != 1]) {
            $this->error("该企业不在有效服务期内！");
        }

        //获取公司加入总人数
        $relatCount = $this->getRelatCount($iCompanyId);
        if ($CompanyInfo['base_num'] <= $relatCount) {
            $this->error("该企业成员已达上限，请联系客服添加！");
        }

        if ($iRoleId == 2) {
            $manageCount = $Relat->where("status >= 0 and role_id = 2 and company_id = $iCompanyId")->count('1');
            if ($manageCount >= 2) {
                $this->error("添加管理员不能超过2个！");
            }
        }
        
        //账号码是否存在
        $userId = $this->userExist($iPhone);
        if (empty($userId)) { //创建新账号，并发送短信提醒
            M()->startTrans();
            $userId = $this->addUser($iPhone,$iPosition);
            $userId && $res = $this->addCompanyRelat($userId,$iCateId,$iRoleId,$iCompanyId);
            if ($res){
                M()->commit();
                $this->sendCode($iPhone,$iCompanyId, 2);
                $this->success('添加成功！');
            } else {
                M()->rollback();
                $this->error('添加失败！');                
            }
        }
        
        $userCount = $Relat->where(array("role_id" => 1, "user_id" => $userId))->count('1');
        if (!empty($userCount)) {
            $this->error('该账号为拥有者账号，不能添加！');
        }

        //已加入企业
        $whereR['user_id'] = $userId;
        $whereR['status'] = array('IN', '0,1');
        $relatRes = $Relat->field('id,company_id,status,company_id')->where($whereR)->find();
        if (!empty($relatRes)) {
            if ($relatRes['company_id'] == $iCompanyId) {
                $this->error('该用户已经加入贵公司!');
            } else {
                $this->error('该用户已被其他企业邀请!');
            }
        }
        
        //在该公司退出或过期，重新加入
        $whereR['status'] = array('IN', '-1,2');
        $whereR['company_id'] = $iCompanyId;
        $eqitRes = $Relat->field('id,company_id,status,company_id')->where($whereR)->find();
        if (!empty($eqitRes)) {
            $res = $this->updateRelat($eqitRes['id'], $iCateId, $iRoleId);
            if ($res) {
                $this->updateUserInfo($userId, $iPosition);
                $this->updatePastCompany($userId);
                $this->sendCode($iPhone,$iCompanyId, 1);
                $this->success("添加成功！");
            }
            $this->error("添加失败！");
        }

        //已注册账号新加入企业成员关联
        M()->startTrans();
        $res = $this->addCompanyRelat($userId,$iCateId,$iRoleId,$iCompanyId);
        $res1 = $this->updateUserInfo($userId, $iPosition);
        if ($res && $res1) {
            M()->commit();
            $this->sendCode($iPhone,$iCompanyId, 1);
            $this->success("添加成功！");
        } else {
            M()->rollback();
            $this->error('添加失败！');
        }
    }

    /**
     *  确认加入企业
     */
    public function affirm() {

        $userID = $this->iUserId;
        $Relat = D('UserCompanyRelat');
        $id = $Relat->where(array('user_id' => $userID, 'company_id' => $this->iCompanyId))->getField('id');

        if (empty($id)) {
            $this->error('您还未加入任何企业');
        }

        $Relat->id = $id;
        $Relat->status = 1;
        $res = $Relat->save();

        $this->success('加入成功！');
    }

    /**
     *  编辑成员
     */
    public function edit() {
        $strRelat_id = $this->getParam('relat_id', '', 'int', true, '关联ID不能我为空');
        $strPosition = $this->getParam('position', '', 'string', true, '请填写职称');
        $strRole_id = I("role_id");
        $strCate_id = I("cate_id");
        if ($strRole_id == '请选择角色')
            $this->error("请选择角色");
        if ($strCate_id == '请选择岗位')
            $this->error("请选择岗位");

        $relatRes = $this->getDetail($strRelat_id);
        if ($strRole_id == 2) {
            if ($this->iRoleId == 2) {
                $this->error("没有权限添加管理员");
            }
            $manageCount = $this->getManageCount($relatRes['company_id']);
            if ($manageCount >= 2 && $relatRes['role_id'] != 2) {
                $this->error("管理员不能超过2个！");
            }
        }

        $Relat = D("UserCompanyRelat");
        $Relat->id = $strRelat_id;
        $Relat->cate_id = $strCate_id;
        $Relat->company_id = $relatRes['company_id'];
        $Relat->role_id = $strRole_id;
        $res = $Relat->save();

        $data['user_id'] = $relatRes['user_id'];
        $data['position'] = $strPosition;
        D('User')->save($data);

        $this->success('编辑成功！');
    }

    /**
     *  成员关联详情
     */
    public function detail() {
        $strRelat_id = I('relat_id', 0, 'intval');
        $company_id = $this->iCompanyId;

        if (empty($strRelat_id)) {
            $this->error('参数错误');
        }

        $where['qy_user_company_relat.company_id'] = $company_id;
        $where['qy_user_company_relat.id'] = $strRelat_id;
        $relatArr = D('UserCompanyRelat')
                ->join('qy_user b on qy_user_company_relat.user_id = b.user_id ')
                ->join('LEFT JOIN qy_category_all d on qy_user_company_relat.cate_id = d.cate_id ')
                ->field('b.phone,
                     qy_user_company_relat.id,
                     qy_user_company_relat.role_id,
                	 d.cate_id,
                     b.position,
                	 d.cate_name'
                )
                ->where($where)
                ->find();
        if ($relatArr['role_id'] == 1) {
            $relatArr['cate_name'] = '运营，客服，美工，营销';
            $relatArr['position'] = $relatArr['position'] ? $relatArr['position'] : '总经理';
        }
        if ($relatArr['role_id'] == 2) {
            $relatArr['cate_name'] = '运营，客服，美工，营销';
        }

        $this->returnList($relatArr);
    }

    /**
     *  移除成员
     */
    public function remove() {
        $strRelat_id = $this->getParam('relat_id', '', 'int', true);

        $Relat = D("UserCompanyRelat");
        $Relat->id = $strRelat_id;
        $Relat->status = -1;
        $res = $Relat->save();

        if ($res) {
            $this->success('移除成功！');
        } else {
            $this->error('移除失败！');
        }
    }

    /**
     *  岗位列表
     */
    public function cateList() {
        $cate_id = I('cate_id', 0, 'intval');

        $cate_id && $where['cate_id'] = $cate_id;
        $relatArr = D('CategoryAll')
            ->field('cate_id,cate_name')
            ->where('type = 1')
            ->where($where)
            ->select();

        $this->returnList($relatArr);
    }

    //获取成员详情
    protected function getCompanyInfo($company_id) {
        $result = D('Company')
            ->field('company_id,user_id,custmer_id,company_name,description,base_num,status,sever_start_time,sever_end_time,sever_stop_time')
            ->where(array('company_id' => $company_id))
            ->find();

        return $result;
    }

    //获取成员详情
    protected function getDetail($iRoleId) {
        $res = M("UserCompanyRelat")
            ->field('company_id,user_id,company_id,user_id,role_id,old_status,status')
            ->where(array('id' => $iRoleId))
            ->find();
        
        return $res;
    }

    //获取管理员数量
    protected function getManageCount($iCompanyId) {
        $where['role_id'] = 2;
        $where['company_id'] = $iCompanyId;
        $where['status'] = array('BETWEEN', '0,1');
        $res = M("UserCompanyRelat")
            ->where($where)
            ->count('1');
        
        return $res;
    }

    //获取公司加入总人数
    protected function getRelatCount($iCompanyId) {
        $where['status'] = array('IN', '0,1');
        $where['company_id'] = $iCompanyId;
        $res = M('UserCompanyRelat')
            ->where($where)
            ->count('1');
        
        return $res;
    }

    //更新企业关系
    protected function updateRelat($id, $iCateId, $iRoleId) {
        $Relat = D("UserCompanyRelat");
        $Relat->id = $id;
        $Relat->cate_id = $iCateId;
        $Relat->role_id = $iRoleId;
        $Relat->status = 0;

        return $Relat->save();
    }

    //更新账户信息
    protected function updateUserInfo($iUserId, $iPosition) {
        $User = D('User');
        $User->user_id = $iUserId;
        $User->position = $iPosition;

        return $User->save();
    }

    //更新其他过期企业
    protected function updatePastCompany($iUserId) {
        $PastRelat = D("UserCompanyRelat");
        $PastRelat->status = -1;
        $PastRelat->where(array('user_id' => $iUserId, 'status' => -1))->save();
    }

    //查询账号码是否注册
    protected function userExist($iPhone) {
        $User = D('User');
        $Uwhere['phone'] = $iPhone;
//         $Uwhere['type'] = array('NEQ',0);
        $res = $User->where($Uwhere)->getField('user_id');

        return $res;
    }

    //添加新账号
    protected function addUser($iPhone,$iPosition) {
        $data = array(
            'phone' => $iPhone,
            'position' => $iPosition,
            'password' => C('INIT_PASSWORD'),
            'type' => 0,
            'create_time' => format_time()
        );
        
        $res = M('User')->add($data);
        return $res;
    }
    
    //添加企业关联
    protected function addCompanyRelat($userId,$iCateId,$iRoleId,$iCompanyId) {
        $data = array(
            'user_id' => $userId,
            'cate_id' => $iCateId,
            'role_id' => $iRoleId,
            'company_id' => $iCompanyId,
            'status' => 0,
            'create_time' => format_time()
        );
        $res = M('UserCompanyRelat')->add($data);
        
        return $res;
    }

    /** 
     *  验证码发送
     *  @internal $iPhone
     */
    protected function sendCode($iPhone,$iCompanyId,$iType) {
        
        $strCompanyName = $this->getCompanyName($iCompanyId);
        $SMS_TPL = C('SMS_TPL');
        if ($iType == 1) {
            $strMessage = str_replace('%company_name%',$strCompanyName,$SMS_TPL[3]);
        } else {
            $strMessage = str_replace('%company_name%',$strCompanyName,$SMS_TPL[4]);
        }
        $res = sys_sms($iPhone,$strMessage);
        return $res;
     }
     
     //获取公司名称
     private function getCompanyName($iCompanyId) {
         $strCompanyName = M("Company")
             ->where(array('company_id'=>$iCompanyId))
             ->getField("company_name");
         
         return $strCompanyName;
     }

}
